//
//  LZCouponManagerListDetailTagsCell.m
//  laziz_Merchant
//
//  Created by xbnzd on 17/1/13.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZCouponManagerListDetailTagsCell.h"
#import "Masonry.h"

static CGFloat kLabelHeight =  18.0;

@interface LZCouponManagerListDetailTagsCell()
@property (weak, nonatomic) IBOutlet UILabel *tagsLabel;  //标签
@property (weak, nonatomic) IBOutlet UIView *tagsBgView;  //标签内容
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tagsBgViewHeight;
@property (strong, nonatomic) NSMutableArray *rowLabelArr;
@property (assign, nonatomic) BOOL beforeLabelIsMaxWidth;//标记上一个label是不是整屏幕宽
@end

@implementation LZCouponManagerListDetailTagsCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    _rowLabelArr = [[NSMutableArray alloc] init];
    self.tagsLabel.text = LZLocalizedString(@"tags", nil);
}

- (void)loadTagsContent:(NSString *)tagsStr
{
    tagsStr = [tagsStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    tagsStr = [tagsStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    if (tagsStr.length == 0) {
        return;
    }
    NSArray *arr = [tagsStr componentsSeparatedByString:@","];
    [self addTagsWithArr:arr.mutableCopy];
    
}

#pragma mark -
#pragma mark 赋值操作
- (void)addTagsWithArr:(NSMutableArray *)tagArr
{
    if (tagArr.count == 0) {
        return;
    }
    
    for (int i = 0; i < tagArr.count; i++) {
        NSString *strTemp = [NSString stringWithFormat:@"%@",tagArr[i]];
        if (strTemp.length == 0) {
            [tagArr removeObject:strTemp];
        }
    }

    _beforeLabelIsMaxWidth = NO;
    if (self.tagsBgView.subviews.count > 0) {
        [self.tagsBgView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    
    CGFloat totleCanShowWidth = [self returnTotleCanShowWidth];
    
    for (int i = 0; i < tagArr.count; i ++) {
        NSString *str = tagArr[i];
        CGFloat strW = [self returnTheNeedLabelWidthStr:str];
        UILabel *strlabel = [self creatTagsLabel];
        strlabel.tag = i + 100;
        strlabel.text = str;
        [self.tagsBgView addSubview:strlabel];
        
        if (strW > totleCanShowWidth) {//如果文字宽度大于可显示范围的宽度
            strW = totleCanShowWidth;
            //标记这一行是全行 同时清空用于存储当前行内容的数组
            _beforeLabelIsMaxWidth = YES;
            if (self.rowLabelArr.count > 0) {
                [self.rowLabelArr removeAllObjects];
            }
            
            //获取上一个label 查看是否之前还有label
            UILabel *beforeLabel = nil;
            if (i >= 1) {
                beforeLabel = [self.tagsBgView viewWithTag:i + 99];
            }
            
            [strlabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.leading.mas_equalTo(0);
                make.size.mas_equalTo(CGSizeMake(strW, kLabelHeight));
                if (beforeLabel != nil) {
                    make.top.equalTo(beforeLabel.mas_bottom).offset(10);
                }else{
                    make.top.mas_equalTo(0);
                }
                
            }];
        }else{//如果文字宽度没有达到最长
            
            //获取当前行一共展示了多少宽度
            CGFloat currentRowLastX = [self returnTheCurrentRowTotleWidth];
            
            //如果新的字符串宽度+当前这行一共的宽度 大于了可显示的宽度,则新起一行
            if (currentRowLastX + strW > totleCanShowWidth) {
                
                //标记当前行是整行 并清空存储当前行内容的数组
                if (self.rowLabelArr.count > 0) {
                    [self.rowLabelArr removeAllObjects];
                }
                
                //获取上一个label
                UILabel *beforeLabel = nil;
                if (i >= 1) {
                    beforeLabel = [self.tagsBgView viewWithTag:i + 99];
                }
                
                [strlabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.leading.mas_equalTo(0);
                    make.size.mas_equalTo(CGSizeMake(strW, kLabelHeight));
                    if (beforeLabel != nil) {
                        make.top.equalTo(beforeLabel.mas_bottom).offset(10);
                    }else{
                        make.top.mas_equalTo(0);
                    }
                    
                }];
                [self.rowLabelArr addObject:str];
                
            }else{//如果新的值 + 当前行的内容值,没有大于可显示的宽度, 则在本行展示
                
                //首先看看这一行前面有没有值, 同时把新值加入到当前行内容数组
                BOOL hasBeforeLabelInCurrentRows = self.rowLabelArr.count > 0 ? YES : NO;
                
                //获取上一个label
                UILabel *beforeLabel = nil;
                if (i >= 1) {
                    beforeLabel = [self.tagsBgView viewWithTag:i + 99];
                }
                [strlabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.size.mas_equalTo(CGSizeMake(strW, kLabelHeight));
                    if (beforeLabel != nil) {
                        if (hasBeforeLabelInCurrentRows) {
                            make.top.equalTo(beforeLabel);
                        }else{
                            make.top.equalTo(beforeLabel.mas_bottom).offset(10);
                        }
                        
                    }else{
                        make.top.mas_equalTo(0);
                    }
                    
                    if (_beforeLabelIsMaxWidth || beforeLabel == nil) {
                        make.leading.mas_equalTo(0);
                    }else{
                        if (hasBeforeLabelInCurrentRows) {
                            make.leading.equalTo(beforeLabel.mas_trailing).offset(10);
                        }else{
                            make.leading.mas_equalTo(0);
                        }
                        
                    }
                }];
                
                [self.rowLabelArr addObject:str];
                _beforeLabelIsMaxWidth = NO;
            }
            
        }
        
        
    }
    if (self.rowLabelArr.count > 0) {
        [self.rowLabelArr removeAllObjects];
    }
    
    [self.tagsBgView layoutIfNeeded];
    UILabel *lastLabel = [self.tagsBgView viewWithTag:tagArr.count + 99];
    self.tagsBgViewHeight.constant = lastLabel.frame.origin.y + 20;
    //    [self.contentView layoutIfNeeded];
    
//    [self.contentView removeConstraint:self.ingredientsContentLabelBottomToTagsBgView];
//    NSLayoutConstraint *topNewCst = [NSLayoutConstraint constraintWithItem:self.ingredientsContentLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.tagsBgView attribute:NSLayoutAttributeTop multiplier:1 constant:-20];
//    [self.contentView addConstraint:topNewCst];
//    
//    
//    
//    [self.contentView removeConstraint:self.desLabelTopToTagsBgViewCST];
//    NSLayoutConstraint *bottomNewCst = [NSLayoutConstraint constraintWithItem:self.descLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.tagsBgView attribute:NSLayoutAttributeBottom multiplier:1 constant:20];
//    [self.contentView addConstraint:bottomNewCst];
}

/*
**
返回当前这一行已经排布了多少宽度

@return <#return value description#>
*/
- (CGFloat)returnTheCurrentRowTotleWidth
{
    CGFloat lastX = 0;
    for (NSString *str in self.rowLabelArr) {
        CGFloat strW = [self returnTheNeedLabelWidthStr:str];
        
        lastX += strW + 10;
    }
    
    return lastX;
}


/**
 返回一串文字应有的宽度
 
 @param str <#str description#>
 @return <#return value description#>
 */
- (CGFloat)returnTheNeedLabelWidthStr:(NSString *)str
{
    CGFloat tagsW = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, kLabelHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.width;
    
    return tagsW + 20;
}


/**
 返回当前屏幕可放置label的最大宽度
 
 @return <#return value description#>
 */
- (CGFloat)returnTotleCanShowWidth
{
    CGFloat tagsW = [LZLocalizedString(@"tags", nil) boundingRectWithSize:CGSizeMake(100, 100) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.width;
    
    return SCREEN_WIDTH - tagsW - 30;
}


/**
 创建一个label
 
 @return <#return value description#>
 */
- (UILabel *)creatTagsLabel
{
    UILabel *l = [[UILabel alloc] init];
    l.backgroundColor = UIColorFromRGB(0xeeeeee, 1);
    l.layer.cornerRadius = kLabelHeight/2;
    l.layer.masksToBounds = YES;
    l.textColor = UIColorFromRGB(0x666666, 1);
    l.font = [UIFont systemFontOfSize:14];
    l.textAlignment = NSTextAlignmentCenter;
    
    return l;
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
